package com.xc.quickstart.manager.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.xc.quickstart.common.constant.RedisKeyConstant;
import com.xc.quickstart.common.exception.CommonBizException;
import com.xc.quickstart.infrastructure.redis.RedisService;
import com.xc.quickstart.manager.wechat.model.QyWechatAccessTokenResponseModel;
import com.xc.quickstart.manager.wechat.model.QyWechatCode2SessionResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author dxl
 */
@Component
@Slf4j
public class QyWechatManager {

    private static final String GRANT_TYPE = "authorization_code";

    @NacosValue("${qywechat.corpid}")
    private String corpId;

    @NacosValue("${qywechat.corpsecret}")
    private String corpSecret;

    @Autowired
    private QyWechatClient qyWechatClient;

    @Autowired
    private RedisService redisService;

    public String getAccessToken() {
        String accessToken = redisService.get(RedisKeyConstant.QY_WECHAT_ACCESS_TOKEN_KEY);
        if (StringUtils.isNotEmpty(accessToken)) {
            return accessToken;
        }

        QyWechatAccessTokenResponseModel responseModel = JSON.parseObject(JSON.toJSONString(qyWechatClient.getAccessToken(corpId, corpSecret)), QyWechatAccessTokenResponseModel.class);
        if (responseModel != null && responseModel.getErrcode().equals(0) && StringUtils.isNotEmpty(responseModel.getAccessToken())) {
            accessToken = responseModel.getAccessToken();
            redisService.setex(RedisKeyConstant.QY_WECHAT_ACCESS_TOKEN_KEY, responseModel.getAccessToken(), Long.valueOf(responseModel.getExpiresIn()), TimeUnit.SECONDS);
            return accessToken;
        }

        throw new CommonBizException("获取企业微信access_token异常！");
    }

    public String getJobNumber(String accessToken, String authorizationCode) {
        QyWechatCode2SessionResponseModel responseModel = qyWechatClient.code2Session(accessToken, authorizationCode, GRANT_TYPE);

        if (responseModel != null && responseModel.getErrcode().equals(0)) {
            return responseModel.getUserid();
        }

        throw new CommonBizException("企业微信临时登录凭证校验异常！");
    }
}
